/*
 * @title: 发起授权
 * @Description:
 * @Author: JZT.饶慧勇
 * @Date: 2025-05-29 09:44:06
 * @LastEditors: JZT.饶慧勇
 * @LastEditTime: 2025-06-10 17:20:24
 */
function useAuthorize() {
  const message = useMessage();
  /**
   * 发起用户授权
   * @param scope 需要获取权限的 scope
   * @param options
   * @param options.success 授权成功的回调
   * @param options.fail 授权失败的回调
   * @param options.showModalTitle 未授权，弹窗提示标题
   * @param options.showModalMsg 未授权，弹窗提示内容
   */
  function sendAuthorize(
    scope: string,
    options: {
      success: () => void;
      fail?: () => void;
      showModalTitle?: string;
      showModalMsg?: string;
    }
  ) {
    // https://developers.weixin.qq.com/miniprogram/dev/api/open-api/privacy/wx.requirePrivacyAuthorize.html
    wx.requirePrivacyAuthorize({
      success: () => {
        console.log('requirePrivacyAuthorize success');
        uni.getSetting({
          success(res) {
            if (res.authSetting[scope]) {
              options.success();
            } else {
              uni.authorize({
                scope,
                success() {
                  options.success();
                },
                fail() {
                  // 没有授权弹窗引导用户进行授权
                  message
                    .confirm({
                      title: options.showModalTitle ?? '授权请求',
                      msg: options.showModalMsg ?? '使用后续功能需要进行授权'
                    })
                    .then(() => {
                      uni.openSetting({
                        success(res) {
                          console.log(res.authSetting);
                          if (res.authSetting[scope]) {
                            options.success();
                          } else {
                            options.fail?.();
                          }
                        },
                        fail() {
                          options.fail?.();
                        }
                      });
                    })
                    .catch(() => {
                      options.fail?.();
                    });
                }
              });
            }
          }
        });
      },
      fail: res => {
        console.error('requirePrivacyAuthorize fail', res);
      }
    });
  }
  return {
    sendAuthorize
  };
}
export default useAuthorize;
